<?php

namespace App\Mobile\Controllers;

include base_path() . '/vendor/autoload.php';
use EasyWeChat\Foundation\Application;
use DB;
use Log;
use Auth;
use Validator;
use Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Redis;
use App\Agent;
use App\Club;
use App\ClubUser;
use App\User;
use App\WxPublicUser;

class FriendCircleController extends Controller
{
	protected $config = [
        'debug' => true,
	    'app_id' => 'wx555be570d21859aa',
	    'secret' => 'f92678be7687d1e1b1471ca9c066f242',
        'token' => '',
    ];

	/**
	 * [index 亲友圈管理]
	 * @return [type] [description]
	 */
	public function index(Agent $agent)
	{
		$user = $agent->user();
		if ($user) {
			$club = Club::where(['creator' => $user->userid])->first();
			if ($club) {
				$members = ClubUser::where(['club_id' => $club->club_id, 'state' => 10])->get();//亲友圈内玩家
				$applys = ClubUser::where(['club_id' => $club->club_id, 'state' => 0])->get();//申请入圈的玩家
				return view('mobile.agent.friendCircle', compact('members', 'applys'));
			}
		}
	}

	/**
	 * [invite 邀请新用户]
	 * @return [type] [description]
	 */
	public function invite(Agent $agent)
	{

		 $user = $agent->user();
		 if ($user) {
		 	$club = Club::where(['creator' => $user->userid])->first();
		 	if ($club) {
		     	$app = new Application($this->config);
				$js = $app->js;
				$url = 'http://user.leyougame.cc/mobile/friend_circle/invite_user';
				if (!file_exists(public_path().'/qrcode/cache_friend_circle/inv_user_'.$agent->id.'.png')) {
				$invite_url = 'http://user.leyougame.cc/mobile/friend_circle/invite_user?cid='.$club->club_id.'&aid='.$agent->id;
				\QrCode::format('png')->size('175')->margin(0)->generate($invite_url, public_path().'/qrcode/cache_friend_circle/inv_user_'.$agent->id.'.png');
				} 
				$img_url = "http://om0fc1nij.bkt.clouddn.com/572407000995670848.jpg?watermark/3/text/".\Qiniu\base64_urlSafeEncode($agent->realname)."/font/5b6u6L2v6ZuF6buR/fill/".\Qiniu\base64_urlSafeEncode('#FFFFFF')."/fontsize/500/dissolve/100/dx/200/dy/20/gravity/NorthWest/image/".\Qiniu\base64_urlSafeEncode($agent->avatar)."/dissolve/100/dx/20/gravity/NorthWest/image/".\Qiniu\base64_urlSafeEncode('http://user.leyougame.cc/qrcode/cache_friend_circle/inv_user_'.$agent->id.'.png')."/dissolve/100/dx/65/dy/50/gravity/SouthEast/";

		         return view('mobile.agent.inviteFriend', compact('agent', 'club', 'js', 'url', 'img_url'));
		 	} else {
		 		Log::info('邀请用户失败, 代理不存在, 时间'.date('Y-m-d H:i:s', time()));
		 	}
		 } else {
		 	Log::info('邀请用户失败, 俱乐部不存在, 时间'.date('Y-m-d H:i:s', time()));
		 }
		
		// return back();
	}

	/**
	 * [audit 审核用户]
	 * @return [type] [description]
	 */
	public function audit(Request $request, ClubUser $clubuser)
	{	
		if (!$request->input('result'))
		{
			return ['flag' => false, 'msg' => '审核结果不能为空!'];
		}
		if ($request->input('result') == 10) {//审核通过
			$member_count = $clubuser->club->memberCount();
			if ($clubuser->club->limitpeople == $member_count) {//亲友圈人数已达上限
				return ['flag' => false, 'msg' => '亲友圈人数已达上限!'];
			}
			$clubuser->state = 10;//通过
			$clubuser->join_time = time();
			$clubuser->save();
			$user = User::where(['userid' => $clubuser->userid])->first();
			if ($user) {
				$wx_user = WxPublicUser::where(['unionid' => substr($user->account, 3)])->first();
				if ($wx_user) {
			        $app = new Application($this->config);
		            $notice = $app->notice;
		            $openId = $wx_user->openid;
		        	$userService = $app->user;
		            $member = $userService->get($openId);
		            $subscribe = $member->subscribe;
		            if ($subscribe) {
			            $templateId = 'q3kyGYoZalQ0fpCF57ipnMO__mwnoXLrZOSZOSQBjDY';
			            $url = "";
			            $data = array(
			                "first" => "恭喜您，您的亲友圈申请，通过审核了!",
			                "keyword1" => "审核通过!",
			                "keyword2" => "会员亲友圈申请",
			                "keyword3" => date('Y-m-d H:i', $clubuser->join_time),
			                "keyword4" => date('Y-m-d H:i', time()),
			                "remark" => "乐游在手，欢乐无忧!",
			            );
			            $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
			        }
				}
			}

			return ['flag' => true];
		} else {//审核拒绝
			$clubuser->state = 1;//拒绝
			$clubuser->save();
			return ['flag' => true];
		}
	}

	/**
	 * [remove 删除亲友圈用户]
	 * @return [type] [description]
	 */
	public function remove(ClubUser $clubuser)
	{
		$clubuser->delete();
		return ['flag' => true];
	}

	/**
	 * [home 亲友圈管理]
	 * @return [type] [description]
	 */
	public function home(Agent $agent)
	{
		$user = $agent->user();
		if ($user) {
			$club = Club::where(['creator' => $user->userid])->whereIn('type', [2,3,4,5,6])->first();
			if ($club) {
				$divide_date = 0;
				$divide_money = 0;
				if (($club->expiry_date/1000) > time()) {//会员还有剩余时间
					$divide_date = ceil((($club->expiry_date / 1000) - time()) / 86400);//剩余天数
					$divide_money = 0;//折现额度
					switch ($club->type) {
						case 2:
							$divide_money = 9.6 * $divide_date;
							break;
						case 3:
							$divide_money = 29.6 * $divide_date;
							break;
						case 4:
							$divide_money = 56 * $divide_date;
							break;
						case 5:
							$divide_money = 72 * $divide_date;
							break;
						case 6:
							$divide_money = 89 * $divide_date;
							break;				
					}
				}
				return view('mobile.agent.circleHome', compact('club', 'agent', 'divide_date', 'divide_money'));
			}
		}
	}

	/**
	 * [create 创建亲友圈]
	 * @return [type] [description]
	 */
	public function create(Agent $agent)
	{
		return view('mobile.agent.createCircle', compact('agent'));
	}

	/**
	 * [store 保存亲友圈]
	 * @return [type] [description]
	 */
	public function store(Agent $agent, Request $request)
	{
        $validator = Validator::make($request->input(), [
            'club_name' => 'required|max:20',
            'description' => 'required|max:100',
            'pay' => 'required',
        ],[
        	'club_name.required' => '亲友圈名称必填',
        	'club_name.max' => '亲友圈名称不超过20字',
        	'description.required' => '简介必填',
        	'description.max' => '简介不超过100字',
        	'pay.required' => '套餐类型必选'
        ]);
        $user = $agent->user();
        if ($user) {
        	$exist = Club::where(['creator' => $user->userid])->whereIn('type', [2, 3, 4, 5])->first();
        	if ($exist) {
	        	$validator->after(function($validator){
		            $validator->errors()->add('club_name', '您已经创建过亲友圈了!');
		        });
        	}
        }
        if ($validator->passes()) {
        	$pay = $request->input('pay');
        	$key = 'club_circle_meal_'.substr(md5(uniqid().time()), 0, 15);
        	$val = json_encode(['club_name' => $request->input('club_name'), 'description' => $request->input('description')]);
        	Redis::del($key);
        	Redis::set($key, $val);
        	Redis::expire($key, 600);

        	header('Location: http://user.leyougame.cc/mobile/agent/payment/?key='.$key.'&pay='.$pay);
        } else {
        	return Redirect::back()->withInput()->withErrors($validator->errors());
        }
	}

	/**
	 * [open 给二级代理开启会员亲友圈]
	 * @return [type] [description]
	 */
	public function open(Agent $agent)
	{
		$agent->open_circle = 1;
		$agent->save();
		return ['flag' => true];
	}


}	